﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Net.Mail;
using System.Collections.Specialized;
using System.Collections;

namespace Autorun
{
	[Serializable]
	public sealed class LogManagement : MarshalByRefObject
	{
		#region "Private members"
		private StringBuilder _dailyReport;
		#endregion

		#region "Singleton Design-Pattern"
		private static LogManagement _instance = new LogManagement();

		public static LogManagement Instance
		{
			get { return _instance; }
		}

		private LogManagement()
		{
			FlushReport();
		}
		#endregion

		#region "Procedures"
		internal void AddEntry(TaskContext context, SeverityLevels severity, string message, object data)
		{
			string query;

			query = string.Format("INSERT INTO tblLog(fktskId, fkschId, logKey, logSeverity, logMessage, logData) VALUES ({0},{1},{2},{3},{4},{5})",
							SqlConvert.SqlId(context.TaskId),
							SqlConvert.SqlId(context.ScheduleId),
							SqlConvert.SqlString(context.Key),
							(int)severity,
							SqlConvert.SqlString(message),
							SqlConvert.SqlString(data));
			ExecuteNonQuery(query);
		}

		internal void AddEntry(SeverityLevels severity, string message, object data)
		{
			string query;

			query = string.Format("INSERT INTO tblLog(logSeverity, logMessage, logData) VALUES ({0},{1},{2})",
																			(int)severity,
																			SqlConvert.SqlString(message),
																			SqlConvert.SqlString(data));
			ExecuteNonQuery(query);
		}

		internal void SendServiceStatus(SeverityLevels severity, ServiceStatuses status, string message)
		{
			SmtpClient client;
			string subject;

			AddEntry(severity, message, null);

			if (ConfigurationManagement.Instance.SendServiceStatus == true)
			{
				client = new SmtpClient(ConfigurationManagement.Instance.SmtpServer, ConfigurationManagement.Instance.SmtpPort);
				client.DeliveryMethod = ConfigurationManagement.Instance.SmtpDeliveryMethod;
				if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
					client.PickupDirectoryLocation = ConfigurationManagement.Instance.SmtpPickupDirectoryLocation;
				subject = string.Format("Autorun - Service status change ({0})", status);
				try
				{
					client.Send(ConfigurationManagement.Instance.MailFrom, ConfigurationManagement.Instance.MailTo, subject, message);
				}
				catch (Exception ex)
				{
					LogManagement.Instance.AddEntry(SeverityLevels.Error, "Error while sending email", string.Format("{0}\n\n\n\n\n{1}\n\n\n\n\n{2}", ex.ToString(), subject, message));
				}
			}
		}

		internal void SendTaskReport(TaskContext context)
		{
			StringBuilder rc;
			SmtpClient client;
			MailMessage msg;
			string subject;
			TaskContext currentContext;

			// === Add the entry into the log ======================================
			AddEntry(context, (context.ExitCode == int.MinValue ? SeverityLevels.Error : SeverityLevels.Verbose), string.Format("Task #{0} stopped with exit code {1}", context.Key, context.ExitCode), context.Error);

			// === Add to the daily report? ========================================
			if (ConfigurationManagement.Instance.SendDailyReport != SendDailyReportModes.Never)
				_dailyReport.Append(BuildTaskHeader(context, true));

			// === Send the task report ============================================
			if ((ConfigurationManagement.Instance.SendTaskReport == SendTaskReportModes.Always) ||
					((ConfigurationManagement.Instance.SendTaskReport == SendTaskReportModes.OnErrors) && (context.ExitCode != 0)))
			{
				rc = new StringBuilder();
				currentContext = context;
				while (currentContext != null)
				{
					rc.AppendLine(GetTaskReport(currentContext));
					currentContext = (currentContext.PreviousContext == null ? null : currentContext.PreviousContext);
				}


				// === Send the email
				subject = string.Format("Autorun - Task report for {0} (Exit code: {1:X8})", context.Caption, context.ExitCode);
				client = new SmtpClient(ConfigurationManagement.Instance.SmtpServer, ConfigurationManagement.Instance.SmtpPort);
				client.DeliveryMethod = ConfigurationManagement.Instance.SmtpDeliveryMethod;
				if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
					client.PickupDirectoryLocation = ConfigurationManagement.Instance.SmtpPickupDirectoryLocation;

				try
				{
					//client.Send(ConfigurationManagement.Instance.MailFrom, ConfigurationManagement.Instance.MailTo, subject, rc.ToString());
					msg = new MailMessage(ConfigurationManagement.Instance.MailFrom, ConfigurationManagement.Instance.MailTo);
					msg.Subject = subject;
					msg.IsBodyHtml = ConfigurationManagement.Instance.SendAsHTML;
					msg.Body = rc.ToString();
					client.Send(msg);
				}
				catch (Exception ex)
				{
					LogManagement.Instance.AddEntry(SeverityLevels.Error, "Error while sending email", string.Format("{0}\n\n\n\n\n{1}\n\n\n\n\n{2}", ex.ToString(), subject, rc.ToString()));
				}
			}
		}

		internal string GetTaskReport(TaskContext context)
		{
			StringBuilder rc;
			//int tskId;
			string query;
			DataTable dt;

			// === Add the entry into the log ======================================
			AddEntry(context, (context.ExitCode == int.MinValue ? SeverityLevels.Error : SeverityLevels.Verbose), string.Format("Task #{0} stopped with exit code {1}", context.Key, context.ExitCode), context.Error);

			//if (context.PreviousContext == null)
			//  tskId = 0;
			//else
			//  tskId = context.PreviousContext.TaskId;

			rc = new StringBuilder();

			// ===================================================================
			// === Report header                                               ===
			// ===================================================================
			rc.Append(BuildTaskHeader(context, false));

			// === Add the log entries ===========================================
			rc.Append(BuildTaskLog(context));

			// === Configuration ===================================================
			rc.Append(BuildTaskConfiguration(context));

			// === Chained parameters ==============================================
			if (context.ChainedParameters != null)
			{
				rc.AppendFormat("\n╔═════════════════════════════════════════════════════════════════════════════╗");
				rc.AppendFormat("\n║ CHAINED PARAMETERS                                                          ║");
				rc.AppendFormat("\n╠═══════════════════════╦═════════════════════════════════════════════════════╣");
				foreach (DictionaryEntry item in context.ChainedParameters)
					rc.AppendFormat("\n║ {0} ║ {1} ║",
							item.Key.ToString().PadRight(21),
							item.Value.ToString().PadRight(51)); // 21, 51
				rc.AppendFormat("\n╚═══════════════════════╩═════════════════════════════════════════════════════╝");
			}

			return rc.ToString();
		}

		private string BuildTaskHeader(TaskContext context, bool forDailyReport)
		{
			if (ConfigurationManagement.Instance.SendAsHTML == false)
				return BuildTaskHeaderPlainText(context, forDailyReport);
			else
				return BuildTaskHeaderHtml(context, forDailyReport);
		}

		private string BuildTaskHeaderPlainText(TaskContext context, bool forDailyReport)
		{
			StringBuilder rc;
			int tskId;

			rc = new StringBuilder();

			if (context.PreviousContext == null)
				tskId = 0;
			else
				tskId = context.PreviousContext.TaskId;

			rc.AppendFormat("\n╔══════════╦══════════╦═══════════════════════════════════════════════════════╗");

			if (forDailyReport == false)
			{
				rc.AppendFormat("\n║  TASK #  ║ {0} ║ CONTEXT KEY                                           ║",
						(tskId == 0 ? "SCHED. #" : "PREV. # "));
				rc.AppendFormat("\n╠══════════╬══════════╬════════════════════════════════════════════╦══════════╣");
				rc.AppendFormat("\n║   FROM   ║    TO    ║ TASK                                       ║ RET.CODE ║");
				rc.AppendFormat("\n╠══════════╬══════════╬════════════════════════════════════════════╩══════════╣");
			}
			rc.AppendFormat("\n║ {0:D8} ║ {1:D8} ║{2}║",
									context.TaskId,
									(tskId != 0 ? tskId : context.ScheduleId),
									context.Key.PadRight(55),
									tskId);
			rc.AppendFormat("\n╠══════════╬══════════╬════════════════════════════════════════════╦══════════╣");
			rc.AppendFormat("\n║ {0} ║ {1} ║ {2} ║ {3:X8} ║",
					context.StartedOn.ToString("HH:mm:ss"),
					context.StoppedOn.ToString("HH:mm:ss"),
					context.Caption.PadRight(42),
					context.ExitCode);
			if (context.ExitCode == 0)
				rc.AppendFormat("\n╚══════════╩══════════╩════════════════════════════════════════════╩══════════╝");
			else
			{
				rc.AppendFormat("\n╟──────────╨──────────╨────────────────────────────────────────────╨──────────╢");
				rc.Append(SplitLine("\n║ {0} ║", context.Error.ToString(), 75));
				rc.AppendFormat("\n╚═════════════════════════════════════════════════════════════════════════════╝");
			}


			return rc.ToString();
		}

		private string BuildTaskHeaderHtml(TaskContext context, bool forDailyReport)
		{
			StringBuilder rc;
			int tskId;

			rc = new StringBuilder();

			if (context.PreviousContext == null)
				tskId = 0;
			else
				tskId = context.PreviousContext.TaskId;

			rc.Append("<table cellpadding=\"1\" cellspacing=\"1\" border=\"1\" width=\"100%\">");

			if (forDailyReport == false)
			{
				rc.AppendFormat("<tr bgcolor=\"#CDCDCD\"><td><b>TASK #</b></td><td><b>{0}</b></td><td colspan=\"2\"><b>CONTEXT KEY</b></td></tr>", (tskId == 0 ? "SCHED. #" : "PREV. # "));
				rc.AppendFormat("<tr bgcolor=\"#CDCDCD\"><td><b>FROM</b></td><td><b>TO</b></td><td><b>TASK</b></td><td><b>RET.CODE</b></td></tr>");
			}

			rc.AppendFormat("<tr><td>{0:D8}</td><td>{1:D8}</td><td colspan=\"2\">{2}</td></tr>",
							context.TaskId,
							(tskId != 0 ? tskId : context.ScheduleId),
							context.Key,
							tskId);

			rc.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3:X8}</td></tr>",
				context.StartedOn.ToString("HH:mm:ss"),
				context.StoppedOn.ToString("HH:mm:ss"),
				context.Caption,
				context.ExitCode);

			if (context.ExitCode != 0)
				rc.AppendFormat("<tr><td colspan=\"4\">{0}</td></tr>", context.Error.ToString().Replace("\n", "<br/>"));

			rc.Append("</table><p>&nbsp;</p>");

			return rc.ToString();
		}

		private string BuildTaskLog(TaskContext context)
		{
			if (ConfigurationManagement.Instance.SendAsHTML == false)
				return BuildTaskLogPlainText(context);
			else
				return BuildTaskLogHtml(context);
		}

		private string BuildTaskLogPlainText(TaskContext context)
		{
			StringBuilder rc;
			string query;
			DataTable dt;

			// =====================================================================
			// === Pre-Process
			// =====================================================================
			rc = new StringBuilder();

			// =====================================================================
			// === Process
			// =====================================================================
			query = string.Format("SELECT * FROM tblLog WHERE logKey={0} ORDER BY logDateTime", SqlConvert.SqlString(context.Key));
			dt = ExecuteDataTable(query);
			if (dt.Rows.Count != 0)
			{
				rc.AppendFormat("\n╔══════════╦══════════╦═══════════════════════════════════════════════════════╗");
				rc.AppendFormat("\n║   TIME   ║   TYPE   ║ MESSAGE                                               ║");
				rc.AppendFormat("\n╠══════════╬══════════╬═══════════════════════════════════════════════════════╣");
				foreach (DataRow dr in dt.Rows)
					rc.Append(SplitLine(string.Format("\n║ {0} ║ {1} ║ {2} ║",
							((DateTime)dr["logDateTime"]).ToString("HH:mm:ss"),
							((SeverityLevels)int.Parse(dr["logSeverity"].ToString())).ToString().PadRight(8),
							"{0}"),
							"\n║          ║          ║ {0} ║",
							dr["logMessage"].ToString(), 53));
				rc.AppendFormat("\n╚══════════╩══════════╩═══════════════════════════════════════════════════════╝");
			}

			// =====================================================================
			// === Post-Process
			// =====================================================================
			return rc.ToString();
		}

		private string BuildTaskLogHtml(TaskContext context)
		{
			StringBuilder rc;
			string query;
			DataTable dt;

			// =====================================================================
			// === Pre-Process
			// =====================================================================
			rc = new StringBuilder();

			// =====================================================================
			// === Process
			// =====================================================================
			query = string.Format("SELECT * FROM tblLog WHERE logKey={0} ORDER BY logDateTime", SqlConvert.SqlString(context.Key));
			dt = ExecuteDataTable(query);
			if (dt.Rows.Count != 0)
			{
				rc.Append("<table cellpadding=\"1\" cellspacing=\"1\" border=\"1\" width=\"100%\">");
				rc.Append("<tr bgcolor=\"#CDCDCD\"><td><b>TIME</b></td><td><b>TYPE</b></td><td><b>MESSAGE</b></td></tr>");
				foreach (DataRow dr in dt.Rows)
					rc.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>",
						((DateTime)dr["logDateTime"]).ToString("HH:mm:ss"),
						((SeverityLevels)int.Parse(dr["logSeverity"].ToString())).ToString().PadRight(8),
						dr["logMessage"]);
				rc.Append("</table><p>&nbsp;</p>");
			}

			// =====================================================================
			// === Post-Process
			// =====================================================================
			return rc.ToString();
		}

		private string BuildTaskConfiguration(TaskContext context)
		{
			if (ConfigurationManagement.Instance.SendAsHTML == false)
				return BuildTaskConfigurationPlainText(context);
			else
				return BuildTaskConfigurationHtml(context);
		}

		private string BuildTaskConfigurationPlainText(TaskContext context)
		{
			StringBuilder rc;

			// =====================================================================
			// === Pre-Process
			// =====================================================================
			rc = new StringBuilder();

			// =====================================================================
			// === Process
			// =====================================================================
			rc.AppendFormat("\n╔═════════════════════════════════════════════════════════════════════════════╗");
			rc.AppendFormat("\n║ CONFIGURATION                                                               ║");
			rc.AppendFormat("\n╠══════════╦══════════════════════════════════════════════════════════════════╣");
			rc.AppendFormat("\n║ CLASS    ║ {0} ║", context.ClassName.PadRight(64));
			rc.AppendFormat("\n║ ASSEMBLY ║ {0} ║", context.AssemblyName.PadRight(64));
			rc.Append(SplitLine("\n║ TITLE    ║ {0} ║", "\n║          ║ {0} ║", context.AssemblyPath, 64));
			//				rc.AppendFormat("\n║ TITLE    ║ {0} ║", context.AssemblyPath.PadRight(64));
			rc.AppendFormat("\n╠══════════╩════════════╦═════════════════════════════════════════════════════╣");
			foreach (DictionaryEntry item in context.Parameters)
				rc.AppendFormat("\n║ {0} ║ {1} ║",
						item.Key.ToString().PadRight(21),
						item.Value.ToString().PadRight(51)); // 21, 51
			rc.AppendFormat("\n╚═══════════════════════╩═════════════════════════════════════════════════════╝");

			// =====================================================================
			// === Post-Process
			// =====================================================================
			return rc.ToString();
		}

		private string BuildTaskConfigurationHtml(TaskContext context)
		{
			StringBuilder rc;

			// =====================================================================
			// === Pre-Process
			// =====================================================================
			rc = new StringBuilder();

			// =====================================================================
			// === Process
			// =====================================================================
			rc.Append("<table cellpadding=\"1\" cellspacing=\"1\" border=\"1\" width=\"100%\">");
			rc.Append("<tr bgcolor=\"#CDCDCD\"><td colspan=\"2\" ><b>CONFIGURATION</b></td></tr>");
			rc.AppendFormat("<tr><td bgcolor=\"#CDCDCD\"><b>CLASS</b></td><td>{0}</td></tr>", context.ClassName);
			rc.AppendFormat("<tr><td bgcolor=\"#CDCDCD\"><b>ASSEMBLY</b></td><td>{0}</td></tr>", context.AssemblyName);
			rc.AppendFormat("<tr><td bgcolor=\"#CDCDCD\"><b>TITLE</b></td><td>{0}</td></tr>", context.AssemblyPath);
			foreach (DictionaryEntry item in context.Parameters)
				rc.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>",
						item.Key,
						item.Value); // 21, 51
			rc.Append("</table><p>&nbsp;</p>");

			// =====================================================================
			// === Post-Process
			// =====================================================================
			return rc.ToString();
		}

		private string BuildTaskChainedParameters(TaskContext context)
		{
			if (ConfigurationManagement.Instance.SendAsHTML == false)
				return BuildTaskChainedParametersPlainText(context);
			else
				return BuildTaskChainedParametersHtml(context);
		}

		private string BuildTaskChainedParametersPlainText(TaskContext context)
		{
			StringBuilder rc;

			// =====================================================================
			// === Pre-Process
			// =====================================================================
			rc = new StringBuilder();

			// =====================================================================
			// === Process
			// =====================================================================
			rc.Append(BuildTaskChainedParameters(context));

			// =====================================================================
			// === Post-Process
			// =====================================================================
			return rc.ToString();
		}

		private string BuildTaskChainedParametersHtml(TaskContext context)
		{
			StringBuilder rc;

			// =====================================================================
			// === Pre-Process
			// =====================================================================
			rc = new StringBuilder();

			// =====================================================================
			// === Process
			// =====================================================================
			if (context.ChainedParameters != null)
			{
				rc.Append("<table cellpadding=\"1\" cellspacing=\"1\" border=\"1\" width=\"100%\">");
				rc.Append("<tr bgcolor=\"#CDCDCD\"><td colspan=\"2\" ><b>CHAINED PARAMETERS</b></td></tr>");
				foreach (DictionaryEntry item in context.ChainedParameters)
					rc.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>",
						item.Key,
						item.Value); // 21, 51
				rc.Append("</table><p>&nbsp;</p>");
			}

			// =====================================================================
			// === Post-Process
			// =====================================================================
			return rc.ToString();
		}

		private string SplitLine(string line, string message, int length)
		{
			return SplitLine(line, line, message, length);
		}

		private string SplitLine(string line1, string line2, string message, int length)
		{
			bool firstDone;
			StringBuilder rc;
			string[] items;
			string item;

			firstDone = false;
			rc = new StringBuilder();
			message = message.Replace("\r", "");
			items = message.Split('\n');

			foreach (string i in items)
			{
				item = i;
				while (item.Length != 0)
				{
					item = item.PadRight(length);
					if (firstDone == false)
						rc.AppendFormat(line1, item.Substring(0, length));
					else
						rc.AppendFormat(line2, item.Substring(0, length));
					firstDone = true;
					item = item.Substring(length);
				}
			}

			return rc.ToString();
		}

		public void FlushReport()
		{
			if (ConfigurationManagement.Instance.SendAsHTML == false)
				FlushReportPlainText();
			else
				FlushReportHtml();
		}

		private void FlushReportPlainText()
		{
			string subject;
			SmtpClient client;
			string body;

			// === If the report is not empty, send it =======================
			if ((ConfigurationManagement.Instance.SendDailyReport == SendDailyReportModes.AlsoEmpty) || ((_dailyReport != null) && (_dailyReport.Length != 0)))
			{
				body = string.Format("{0}{1}{2}{3}{4}{5}",
						"\n╔══════════╦══════════╦═══════════════════════════════════════════════════════╗",
						"\n║  TASK #  ║ SCHED. # ║ CONTEXT KEY                                           ║",
						"\n╠══════════╬══════════╬════════════════════════════════════════════╦══════════╣",
						"\n║   FROM   ║    TO    ║ TASK                                       ║ RET.CODE ║",
						"\n╚══════════╩══════════╩════════════════════════════════════════════╩══════════╝",
						_dailyReport);

				// === Send the email
				subject = string.Format("Autorun - Daily report for {0}", DateTime.Now.AddDays(0).ToString("dd/MM/yyyy"));
				client = new SmtpClient(ConfigurationManagement.Instance.SmtpServer, ConfigurationManagement.Instance.SmtpPort);
				client.DeliveryMethod = ConfigurationManagement.Instance.SmtpDeliveryMethod;
				if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
					client.PickupDirectoryLocation = ConfigurationManagement.Instance.SmtpPickupDirectoryLocation;

				try
				{
					client.Send(ConfigurationManagement.Instance.MailFrom, ConfigurationManagement.Instance.MailTo, subject, body);
				}
				catch (Exception ex)
				{
					LogManagement.Instance.AddEntry(SeverityLevels.Error, "Error while sending email", string.Format("{0}\n\n\n\n\n{1}\n\n\n\n\n{2}", ex.ToString(), subject, body));
				}

			}

			// === Start a new report =======================================
			_dailyReport = new StringBuilder();
		}

		private void FlushReportHtml()
		{
			string subject;
			SmtpClient client;
			StringBuilder body;
			MailMessage msg;

			// === If the report is not empty, send it =======================
			if ((ConfigurationManagement.Instance.SendDailyReport == SendDailyReportModes.AlsoEmpty) || ((_dailyReport != null) && (_dailyReport.Length != 0)))
			{
				body = new StringBuilder();

				body.Append("<table cellpadding=\"1\" cellspacing=\"1\" border=\"1\" width=\"100%\">");
				body.Append("<tr bgcolor=\"#CDCDCD\"><td><b>TASK #</b></td><td><b>SCHED #</b></td><td colspan=\"2\"><b>CONTEXT KEY</b></td></tr>");
				body.Append("<tr bgcolor=\"#CDCDCD\"><td><b>FROM</b></td><td><b>TO</b></td><td><b>TASK</b></td><td><b>RET.CODE</b></td></tr>");
				body.Append("<p>&nbsp;</p>");
				body.Append(_dailyReport);
				body.Append("</table>");

				// === Send the email
				subject = string.Format("Autorun - Daily report for {0}", DateTime.Now.AddDays(0).ToString("dd/MM/yyyy"));
				client = new SmtpClient(ConfigurationManagement.Instance.SmtpServer, ConfigurationManagement.Instance.SmtpPort);
				client.DeliveryMethod = ConfigurationManagement.Instance.SmtpDeliveryMethod;
				if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory)
					client.PickupDirectoryLocation = ConfigurationManagement.Instance.SmtpPickupDirectoryLocation;

				try
				{
					//client.Send(ConfigurationManagement.Instance.MailFrom, ConfigurationManagement.Instance.MailTo, subject, body);
					msg = new MailMessage(ConfigurationManagement.Instance.MailFrom, ConfigurationManagement.Instance.MailTo);
					msg.Subject = subject;
					msg.IsBodyHtml = ConfigurationManagement.Instance.SendAsHTML;
					msg.Body = body.ToString();
					client.Send(msg);
				}
				catch (Exception ex)
				{
					LogManagement.Instance.AddEntry(SeverityLevels.Error, "Error while sending email", string.Format("{0}\n\n\n\n\n{1}\n\n\n\n\n{2}", ex.ToString(), subject, body));
				}

			}

			// === Start a new report =======================================
			_dailyReport = new StringBuilder();
		}

		public void ClearLog()
		{
			string query;

			query = "DELETE FROM tblLog";
			ExecuteNonQuery(query);
		}

		public void ClearLog(SeverityLevels severityLevel)
		{
			string query;

			query = string.Format("DELETE FROM tblLog WHERE logSeverity={0}", (int)severityLevel);
			ExecuteNonQuery(query);
		}
		#endregion

		#region "Properties"
		public DataTable LogEntries
		{
			get
			{
				DataTable rc;
				string query;

				query = "SELECT logId, fkschId, fktskId, (SELECT tskCaption FROM tblTask WHERE tskId=fktskId) AS tskCaption, logKey, logDateTime, logSeverity, CASE logSeverity WHEN 0 THEN 'Verbose' WHEN 1 THEN 'Information' WHEN 2 THEN 'Warning' WHEN 4 THEN 'Error' ELSE '???' END AS logSeverityCaption, logMessage, logData FROM tblLog ORDER BY logDateTime DESC, logKey";
				rc = ExecuteDataTable(query);

				return rc;
			}
		}

		public int LogEntriesCount
		{
			get
			{
				string query;
				int rc;

				query = "SELECT COUNT(*) FROM tblLog";
				rc = (int)ExecuteScalar(query);

				return rc;
			}
		}
		#endregion

		#region "Data Access Methods"
		private void ExecuteNonQuery(string query)
		{
			SqlConnection cn;
			SqlCommand cmd;

			cn = new SqlConnection(Properties.Settings.Default.ConnectionString);

			try
			{
				cn.Open();
				cmd = cn.CreateCommand();
				cmd.CommandText = query;
				cmd.ExecuteNonQuery();
				cmd.Connection = null;
				cmd = null;
			}
			finally
			{
				cn.Close();
			}
		}

		private object ExecuteScalar(string query)
		{
			SqlConnection cn;
			SqlCommand cmd;
			object rc = null;

			cn = new SqlConnection(Properties.Settings.Default.ConnectionString);

			try
			{
				cn.Open();
				cmd = cn.CreateCommand();
				cmd.CommandText = query;
				rc = cmd.ExecuteScalar();
				cmd.Connection = null;
				cmd = null;
			}
			finally
			{
				cn.Close();
			}

			return rc;
		}

		private DataTable ExecuteDataTable(string query)
		{
			SqlDataAdapter da;
			DataSet rc;

			da = new SqlDataAdapter(query, Properties.Settings.Default.ConnectionString);
			rc = new DataSet();
			da.Fill(rc);
			return rc.Tables.Count != 0 ? rc.Tables[0] : null;
		}
		#endregion
	}
}
